package org.tsinghua.answer.domain.question;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

public interface QuestionRepository extends PagingAndSortingRepository<Question, String> {
	
	@Query("select q from Question q where q.creator.id = :creator"
			+ " and (q.title like :keyword or q.description like :keyword)"
			+ " and q.status = :status"
			+ " order by q.modifyTime DESC")
	public Page<Question> userQuestions(@Param("creator")String id, @Param("keyword") String keyword,
			@Param("status") QuestionStatus status, Pageable pageable);
	
	@Query("select q from Question q join q.creator c"
			+ " where q.status = :status"
			+ " and (q.title like :keyword or q.description like :keyword)"
			+ " order by q.modifyTime DESC")
	public Page<Question> findByStatus(@Param("status") QuestionStatus status, 
			@Param("keyword") String keyword, 
			Pageable pageable);
	
	@Query("select q from Question q join q.creator c"
			+ " where q.status = :status"
			+ " and q.subjectId = :subjectId"
			+ " and (q.title like :keyword or q.description like :keyword)"
			+ " order by q.modifyTime DESC")
	public Page<Question> findByStatusAndSubject(@Param("status") QuestionStatus status, 
			@Param("subjectId")String subjectId, 
			@Param("keyword")String keyword, Pageable pageable);
	
	@Query("select distinct q from Question q join q.replies r"
			+ " where r.creator.id = :volunteerId"
			+ " and (q.title like :keyword or q.description like :keyword)")
	public Page<Question> volunteerQuestions(@Param("volunteerId")String volunteerId, 
			@Param("keyword") String keyword, 
			Pageable pageable);
	
	@Query("select distinct q from Question q join q.replies r"
			+ " where r.creator.id = :volunteerId"
			+ " and q.subjectId = :subjectId"
			+ " and (q.title like :keyword or q.description like :keyword)")
	public Page<Question> volunteerQuestions(@Param("volunteerId")String volunteerId, 
			@Param("subjectId") String subjectId,
			@Param("keyword") String keyword, 
			Pageable pageable);
}
